package com.txby.platformApi.component.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jck.mybatis.util.PageList;
import com.jck.tools.ChkUtil;
import com.jck.tools.easyui.DateUtils;
import com.txby.platformCore.component.service.CommonController;
import com.txby.platformCore.component.util.MathUtil;
import com.txby.platformCore.data.CommonApiModelMapExt;
import com.txby.platformCore.entity.InHosBill;
import com.txby.platformCore.entity.SickCheckResultInfo;
import com.txby.platformCore.entity.SickDetailInfo;
import com.txby.platformCore.entity.TxbyBDApiConfig;

import io.swagger.annotations.Api;

/**
 * 医院每日清单信息
* @author 作者 jacking
* @date  
 */
@SuppressWarnings("all")
@RestController
@Api(value="医院每日清单信息",description="医院每日清单信息-说明")
@RequestMapping("/hosBill")
public class HosBillController extends CommonController{
	private static Logger log = Logger.getLogger(HosBillController.class);
	 

	@GetMapping("/getInHosBill/{type}/{token}")
	public Map getInHosBill(@PathVariable("type") Integer type, @PathVariable("token") String token,String detailTime,@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		SickDetailInfo sdi;
		try {
			if (!isTokenValid) {
				return mm;
			}
			sdi = getSickDetailInfo(deviceSN);
			String inHosNO = sdi.getInHosNO();
			 
			Map paramMap = new HashMap<>();
			String searchSql = "";
			// 日期为空,取当前日期前一天的日期为值
			if(ChkUtil.isEmpty(detailTime)) {
				detailTime=DateUtils.format(DateUtils.addDays(new Date(),-1), DateUtils.YYYYMMDD_10);
			}
			
			if (!ChkUtil.isEmpty(detailTime)) {
				searchSql += " and a.detailTime<=  #{pojo.detailTime} ";
				paramMap.put("detailTime",  detailTime);
			}
			paramMap.put("inHosNO",  sdi.getInHosNO());
			searchSql += " order by a.inHosTime desc";//默认入院时间倒序
			PageList pl=new PageList<>();
//			查询job接口是否异常， 如果异常 则只取本地数据库
//			this.isHisErr(SickCheckResultInfo.class.getName());
			List<SickCheckResultInfo> oInfoList=new ArrayList<>();
			Map dataMap=new HashMap();
			if(propertySourceConfig.getIsExecuteHisHttp()!=null&&propertySourceConfig.getIsExecuteHisHttp().equals("true")&&!isHisErr){
				List<TxbyBDApiConfig> bdInfoList=this.getTxbyBDApiConfigInfo(TxbyBDApiConfig.class.getName());
				if(!ChkUtil.isEmptyAllObject(bdInfoList)){
					TxbyBDApiConfig bdInfo=bdInfoList.get(0);
					Map jo=JSON.parseObject(bdInfo.getApiParam());
				    String json=this.getHttpResponseContent(bdInfo.getApiBaseUrl()+bdInfo.getApiServletPath(), "get",paramMap);
				    JSONObject jsonData=JSON.parseObject(json);
				     CommonApiModelMapExt temp= new CommonApiModelMapExt();
				     BeanUtils.copyProperties(temp, jsonData);
				    if(temp.getCode()==1){
				    	Map dataO=new HashMap();
				    	SickCheckResultInfo oInfo=new SickCheckResultInfo();
				    	BeanUtils.copyProperties(oInfo, jsonData);
				    	 Object o = jsonData.get("data");
                        if(!(o instanceof JSONArray)){
                        	BeanUtils.copyProperties(oInfo, o);
                        	oInfoList.add(oInfo);
                        }else{
                        	List oList=(List) o;
                        	for(Object obj:oList){
                        		oInfo=new SickCheckResultInfo();
                    			BeanUtils.copyProperties(oInfo, obj);
                    			oInfoList.add(oInfo);
                        	}
                        	
                        	//保存数组
                        }
				    	
				    }
				    
//				    循环处理
				    for(SickCheckResultInfo sbi:oInfoList){
				    	List<SickCheckResultInfo> oldObj=this.mBaseDao.findBySql("select * from  "+mBaseDao.tableName(SickCheckResultInfo.class)+" where 1=1   "+searchSql, SickCheckResultInfo.class, paramMap);
				    	SickCheckResultInfo oInfo=new SickCheckResultInfo();
				    	if(oldObj.size()>0){
				    		oInfo= oldObj.get(0);
				    		String id=oInfo.getId();
				    		BeanUtils.copyProperties(oInfo, sbi);
				    		oInfo.setId(id);
				    		oInfo.setUpdateTime(new Date());
				    		this.mBaseDao.updateObject(oInfo);
				    	}else{
				    		this.mBaseDao.saveObject(sbi);
				    	}
				    }
					
				}
				
				pl =new PageList<>(oInfoList, null);
				
			}else{
				String sql="SELECT * FROM t_txby_inHosBill i JOIN t_txby_inHosBill_detail de ON i.id = de.inHosBillId "
						 + "AND i.inHosNO = #{pojo.inHosNO}"
						 +" AND date_format(de.detailTime, '%Y-%m-%d') = #{pojo.detailTime} order by de.detailTime desc";
				pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, null, paramMap);
				
/*				if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
					mm.put(CommonApiModelMapExt.ERRCODE, 4500);
					mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
					mm.put("data", pl.getResultList());
					return mm;
				}*/
				List detailList=pl.getResultList();
				Double inHosTotalMoney = Double.valueOf(0.00d);
				for(Object o:detailList) {
					Map m = (Map)o;
					Double v1=Double.valueOf(m.get("detailTotalMoney")+"");
					inHosTotalMoney=MathUtil.add(inHosTotalMoney, v1);
				}
				InHosBill inHosBill=new InHosBill();
				inHosBill.setInHosTotalMoney(inHosTotalMoney);
				inHosBill.setInHosTime(sdi.getInHosTime());
				inHosBill.setSickAreaName(sdi.getSickAreaName());
				inHosBill.setBedNO(sdi.getBedNO());
				inHosBill.setDeptName(sdi.getDeptNOName());
				inHosBill.setMainCureDoctor(sdi.getMgBedDoctor());
				inHosBill.setInHosNO(sdi.getInHosNO());
				dataMap.put("baseInfo", inHosBill);
				dataMap.put("data", pl.getResultList());
			}
			/**
			 * 请求http数据api
			 */
			
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", dataMap);
			return mm;
			
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 1);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}

	@GetMapping("/getInHosBillDayList/{type}/{token}")
	public Map getInHosBillDayList(@PathVariable("type") Integer type, @PathVariable("token") String token,@RequestParam(required=true,name="deviceSN") String deviceSN) {
		CommonApiModelMapExt mm = chekTokenCahceValid(token, type);
		try {
			if (!isTokenValid) {
				return mm;
			}
			PageList pl=new PageList<>();
			SickDetailInfo sdi = getSickDetailInfo(deviceSN);
			String inHosNo = sdi.getInHosNO();
			Map paramMap = new HashMap<>();
			paramMap.put("inHosNo", inHosNo);
	
			String sql="SELECT SUM(t.detailTotalMoney) detailTotalMoney, date_format(t.detailTime, '%Y-%m-%d') detailTime FROM ("
					+" SELECT d.detailTotalMoney,d.detailTime FROM t_txby_inHosBill_detail d,t_txby_inHosBill i WHERE i.inHosNO = '"+inHosNo+"' AND d.inHosBillId = i.id and date_format(d.detailTime, '%Y-%m-%d')<date_format(now(), '%Y-%m-%d')) t "
					+ "GROUP BY date_format(t.detailTime, '%Y-%m-%d') ORDER BY detailTime DESC" ;
			pl = this.mBaseDao.findBySqlForPageList(sql, Map.class, null, paramMap);
			if(pl==null || pl.getResultList()==null || pl.getResultList().size()==0) {
				mm.put(CommonApiModelMapExt.ERRCODE, 4500);
				mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
				mm.put("data", pl.getResultList());
				return mm;
			}
			mm.put(CommonApiModelMapExt.ERRCODE, 0);
			mm.put(CommonApiModelMapExt.ERRMSG, "查询成功");
			mm.put("data", pl.getResultList());
			return mm;
		} catch (Exception e) {
			e.printStackTrace();
			mm.put(CommonApiModelMapExt.ERRCODE, 5000);
			mm.put(CommonApiModelMapExt.ERRMSG, "系统异常");
		}
		return mm;
	}
	
	


}